package me.shurufa.fragments;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.malinskiy.superrecyclerview.SuperRecyclerView;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.HttpRequest;
import de.greenrobot.event.EventBus;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import me.shurufa.R;
import me.shurufa.activities.NewDigestActivity;
import me.shurufa.adapter.DiscoveryAdapter;
import me.shurufa.bean.Book;
import me.shurufa.controller.CounterController;
import me.shurufa.controller.DataController;
import me.shurufa.net.API;
import me.shurufa.net.RequestParams;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.BookListResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.NetworkUtils;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.HeaderWithSearchBar;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.floatingactionbutton.FloatingActionButton;
import me.shurufa.widget.floatingactionbutton.FloatingActionsMenu;
import me.shurufa.widget.pulltorefresh.SrfPtrFrameLayout;
import me.shurufa.widget.recyclerview.EndlessRecyclerOnScrollListener;
import me.shurufa.widget.recyclerview.HeaderAndFooterRecyclerViewAdapter;
import me.shurufa.widget.recyclerview.HeaderSpanSizeLookup;

/**
 * 作者 : andy
 * 日期 : 16/3/8 17:50
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 书摘最近添加Fragment
 */
public class DiscoveryFragment extends BaseFragment implements View.OnClickListener {

    @Bind(R.id.tv_header_title)
    TextView tv_header_title;

    @Bind(R.id.left_text)
    TextView leftText;

    @Bind(R.id.right_text)
    TextView rightText;

    @Bind(R.id.recycler_view)
    SuperRecyclerView recyclerView;

    @Bind(R.id.ptr_refresh)
    SrfPtrFrameLayout ptrRefresh;

    @Bind(R.id.fab_menu)
    FloatingActionsMenu mFabMenu;

    @Bind(R.id.fab_add_digest)
    FloatingActionButton mFabAddDigset;

    @Bind(R.id.fab_add_notebook)
    FloatingActionButton mFabAddNotebook;

    @Bind(R.id.header_with_search)
    HeaderWithSearchBar header_with_search;

    @Bind(R.id.ll_overlay)
    LinearLayout mOverlayLayout;

    private Handler mHandler = new Handler();
    private ArrayList<Book> mDataList;
    private DiscoveryAdapter discoveryAdapter;

    private String mSearchContent = "";  // 搜索内容
    private int mFragmentType;
    private int mPage;

    private long mLastTime;
    private boolean hasMore = true;
    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (NetworkUtils.isNetAvailable(getActivity())) {
                RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                loadData(mPage);
            }
        }
    };


    /**
     * @param fragType 类型
     * @return DiscoveryFragment
     */
    public static DiscoveryFragment newInstance(int fragType) {
        DiscoveryFragment fragment = new DiscoveryFragment();
        Bundle args = new Bundle();
        args.putInt(Constants.TYPE_FRAGMENT, fragType);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_new_book_comment, container, false);
        ButterKnife.bind(this, view);
        parseArguments();
        return view;
    }

    private void parseArguments() {
        if (getArguments() != null) {
            mFragmentType = getArguments().getInt(Constants.TYPE_FRAGMENT, Constants.TYPE_FRAGMENT_NEWEST_BOOK);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 自动刷新一次
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (null != ptrRefresh) {
                    ptrRefresh.autoRefresh(true);
                }
            }
        }, 400);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (null != header_with_search) {
            header_with_search.reset();
        }
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        //        初始化刷新
        setRefresh();
        tv_header_title.setText(getTitleText());

        mDataList = new ArrayList<>();
        discoveryAdapter = new DiscoveryAdapter(getActivity(), mDataList, mFragmentType);
        HeaderAndFooterRecyclerViewAdapter mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(discoveryAdapter);

        //setLayoutManager
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 3);
        manager.setSpanSizeLookup(new HeaderSpanSizeLookup(mHeaderAndFooterRecyclerViewAdapter, manager.getSpanCount()));
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
        recyclerView.getEmptyView().setVisibility(View.GONE);
        recyclerView.setOnScrollListener(mOnScrollListener);
        recyclerView.getRecyclerView().setOverScrollMode(View.OVER_SCROLL_NEVER);

        leftText.setVisibility(View.VISIBLE);
        rightText.setVisibility(View.GONE);
        leftText.setText(getString(R.string.new_build));
        rightText.setText(getString(R.string.go_discover));
        leftText.setOnClickListener(this);
        rightText.setOnClickListener(this);

        mOverlayLayout.setOnClickListener(this);
        mFabMenu.setOnFloatingActionsMenuUpdateListener(new FloatingActionsMenu.OnFloatingActionsMenuUpdateListener() {
            @Override
            public void onMenuExpanded() {
                startOverlayAnimIn();
            }

            @Override
            public void onMenuCollapsed() {
                startOverlayAnimOut();
            }
        });
        mFabAddDigset.setOnClickListener(this);
        mFabAddNotebook.setOnClickListener(this);

        if (mFragmentType == Constants.TYPE_FRAGMENT_MYSHELF
                || mFragmentType == Constants.TYPE_FRAGMENT_MYCOLLECT
                || mFragmentType == Constants.TYPE_FRAGMENT_MYCOMMENT) {

            header_with_search.setOnSearchListener(new HeaderWithSearchBar.OnSearchListener() {
                @Override
                public void onSearch(String content) {
                    mSearchContent = content;
                    if (!TextUtils.isEmpty(mSearchContent)) {
                        refresh();
                    }
                }

                @Override
                public void onBack() {
                    mSearchContent = "";
                    refresh();
                }
            });
        } else {
            header_with_search.hideSearch();
        }
    }

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);

            try {
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(recyclerView.getRecyclerView());
                if(state == LoadingFooter.State.Loading) {
                    LogUtils.kLog().e("the state is Loading, just wait..");
                    return;
                }

                if (hasMore) {
                    if (!NetworkUtils.isNetAvailable(getActivity())) {
                        RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.NetWorkError, mFooterClick);
                        return;
                    }
                    // loading more
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                    loadData(mPage);
                } else {
                    //the end
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private void setRefresh() {
        ptrRefresh.setResistance(2.0F);
        ptrRefresh.setRatioOfHeaderHeightToRefresh(1.0F);
        ptrRefresh.setDurationToClose(300);
        ptrRefresh.setDurationToCloseHeader(500);
        ptrRefresh.setLoadingMinTime(500);
        ptrRefresh.setPullToRefresh(false);
        ptrRefresh.setKeepHeaderWhenRefresh(true);
        ptrRefresh.disableWhenHorizontalMove(true);
        ptrRefresh.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
                return PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, ((SuperRecyclerView) view).getRecyclerView(), view1);
            }
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                refresh();
            }
        });
    }

    //Load and Refresh
    @Override
    public void refresh() {
        if (ptrRefresh!=null&&ptrRefresh.isRefreshing()) {
            ptrRefresh.refreshComplete();
        }

        // process request
        mPage = 1;
        mLastTime = 0;
        loadData(mPage);
    }

    /**
     * 重置搜索条
     */
    public void resetSearchBar() {
        if (header_with_search.getEditText().isFocused()) {
            header_with_search.reset();
            Utils.closeInputMethod(getActivity(), header_with_search.getEditText());
        }
    }

    /**
     * 加载数据
     * @param page 页码
     */
    private void loadData(final int page) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("page", page);
        params.addFormDataPart("last_time", mLastTime);

        if (!TextUtils.isEmpty(mSearchContent)) {
            params.addFormDataPart("keyword", mSearchContent);
        }

        HttpRequest.post(getApi(), params, new HttpCallback<BookListResp>() {

            @Override
            public void onRespSuccess(BookListResp bookListResp) {
                try {
                    handleResponse(bookListResp, (page == 0 || page == 1));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(BookListResp bookListResp) {

            }

            @Override
            public void onStart() {
                super.onStart();
                if (NetworkUtils.isNetAvailable(getActivity())) {
                    RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), LoadingFooter.State.Loading);
                } else {
                    // 是上拉加载
                    if (mPage > 1) {
                        RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.NetWorkError, mFooterClick);
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                try {
                    refreshComplete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 处理返回结果
     * 1. 去重
     * @param bookListResp     data
     * @param isPullToRefresh  boolean
     */
    private void handleResponse(BookListResp bookListResp, boolean isPullToRefresh) {
        // 是否还有更多
        hasMore = !(bookListResp.data == null || Utils.isNullForList(bookListResp.data));

        // 若搜索不为空 则先清空列表数据
        if (!TextUtils.isEmpty(mSearchContent)) {
            discoveryAdapter.clear();
            discoveryAdapter.notifyDataSetChanged();
        }

        // 1. 判空
        if (bookListResp.data == null || Utils.isNullForList(bookListResp.data)) {
            if (isPullToRefresh) {
                recyclerView.getEmptyView().setVisibility(View.VISIBLE);
            }
            return;
        }

        // 2. 去重
        if (!isPullToRefresh) {
            bookListResp.data = DataController.getValidDataList(mDataList, bookListResp.data);
        } else {
            discoveryAdapter.clear();
            discoveryAdapter.notifyDataSetChanged();
        }

        // 3. 添加进列表并刷新
        discoveryAdapter.append(bookListResp.data);

        // 4. 更新分页信息
        mLastTime = Utils.isNullForList(mDataList) ? 0 : mDataList.get(mDataList.size() - 1).updated_at;

        // 5. 页码自增
        mPage ++;
        mLastTime = (Utils.isNullForList(mDataList)) ? 0 : mDataList.get(mDataList.size() - 1).updated_at;

    }

    /**
     * Require run in UIThread
     */
    public void refreshComplete() {
        // 是上拉加载更多
        if (mPage > 1) {
            RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), hasMore ? LoadingFooter.State.Normal : LoadingFooter.State.TheEnd);
        }

        // 是下拉加载
        if (ptrRefresh != null && mPage <= 1) {
            ptrRefresh.refreshComplete();
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()){
            case R.id.book_img:
                Utils.showToast(R.string.my_favourite_digest);
                break;
            case R.id.left_text:
                intent = new Intent(getActivity(), NewDigestActivity.class);
                startActivity(intent);
                break;
            case R.id.right_text:
                intent = new Intent(Constants.ACTION_MAIN_SWITCH);
                intent.putExtra(Constants.EXTRA_SWITCH_INDEX,0);
                EventBus.getDefault().post(intent);
                break;
            case R.id.fab:
                EventBus.getDefault().post(new Intent(Constants.EVENT_MAIN_MENU));
                break;

            case R.id.ll_overlay:
                if (mFabMenu.isExpanded()) {
                    startOverlayAnimOut();
                    mFabMenu.collapse();
                }
                break;

            case R.id.fab_add_digest:
                mFabMenu.collapse();

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        EventBus.getDefault().post(new Intent(Constants.EVENT_MAIN_MENU_ADD_DIGEST));
                    }
                }, 300);

                break;
            case R.id.fab_add_notebook:
                mFabMenu.collapse();

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        EventBus.getDefault().post(new Intent(Constants.EVENT_MAIN_MENU_ADD_NOTEBOOK));
                    }
                }, 300);

                break;
        }
    }

    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (Constants.ACTION_BOOKSHELVES_REFRESH.equals(intent.getAction()) ||Constants.ACTION_ADD_DIGEST_COMPLETE.equals(intent.getAction())){
            refresh();
        }

        int bookId = intent.getIntExtra(Constants.ARG_BOOK_ID, 0);

        // 添加书评
        if (Constants.EVENT_SEND_BOOK_COMMENT.equals(intent.getAction())) {
            CounterController counterController = new CounterController(discoveryAdapter, mDataList, bookId, CounterController.CounterType.BOOKCOMMENT);
            counterController.handleAddCounter();
        }

        // 删除书评
        if (Constants.EVENT_DEL_BOOK_COMMENT.equals(intent.getAction())) {
            CounterController counterController = new CounterController(discoveryAdapter, mDataList, bookId, CounterController.CounterType.BOOKCOMMENT);
            counterController.handleDelCounter();
        }

        // 删除书摘
        if (Constants.EVENT_DEL_BOOK_DIGEST.equals(intent.getAction())) {
            CounterController counterController = new CounterController(discoveryAdapter, mDataList, bookId, CounterController.CounterType.DIGEST);
            counterController.handleDelCounter();
        }

    }

    private void startOverlayAnimIn() {
        mOverlayLayout.setVisibility(View.VISIBLE);
        ObjectAnimator animator = ObjectAnimator.ofFloat(mOverlayLayout, "alpha", 0.0f, 1.0f);
        animator.setDuration(150);
        animator.start();
    }

    private void startOverlayAnimOut() {

        ObjectAnimator animator = ObjectAnimator.ofFloat(mOverlayLayout, "alpha", 1.0f, 0f);
        animator.setDuration(150);
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mOverlayLayout.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.start();
    }

    /**
     * 根据类型获得对应的URL
     * @return url
     */
    public String getApi() {
        switch (mFragmentType) {
            case Constants.TYPE_FRAGMENT_NEWEST_BOOK:
                return API.GET_TOP_BOOK;
            case Constants.TYPE_FRAGMENT_MOST_EXCERPT:
                return API.GET_BOOK_MOST_EXCERPT;
            case Constants.TYPE_FRAGMENT_MOST_COMMENT:
                return API.GET_BOOK_MOST_COMMENT;
            case Constants.TYPE_FRAGMENT_MYSHELF:
                return API.GET_MY_SHELF_LIST;
            case Constants.TYPE_FRAGMENT_MYCOLLECT:
                return API.GET_MY_COLLECT_LIST;
            case Constants.TYPE_FRAGMENT_MYCOMMENT:
                return API.GET_MY_COMMENT_LIST;
            default:
                return API.GET_TOP_BOOK;
        }
    }

    /**
     * 获得标题文字 resId
     * @return resId
     */
    public int getTitleText() {
        switch (mFragmentType) {
            case Constants.TYPE_FRAGMENT_NEWEST_BOOK:
                return R.string.header_recent_add;
            case Constants.TYPE_FRAGMENT_MOST_EXCERPT:
                return R.string.header_most_digest;
            case Constants.TYPE_FRAGMENT_MOST_COMMENT:
                return R.string.header_most_comment;
            case Constants.TYPE_FRAGMENT_MYSHELF:
                return R.string.header_my_shelf;
            case Constants.TYPE_FRAGMENT_MYCOLLECT:
                return R.string.header_my_collect;
            case Constants.TYPE_FRAGMENT_MYCOMMENT:
                return R.string.header_my_commented;
            default:
                return R.string.header_recent_add;
        }
    }
}
